package com.ysjy.course.service.impl;

import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.PromptMessage;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.course.CourseClassDto;
import com.wkbb.common.utils.DateUtil;
import com.wkbb.common.utils.RandomUtil;
import com.ysjy.course.mapper.CourseClassMapper;
import com.ysjy.course.mapper.TrusteeshipMapper;
import com.ysjy.course.model.OrgCourse;
import com.ysjy.course.model.YsTrusteeship;
import com.ysjy.course.service.TrusteeshipService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class TrusteeshipServiceImpl extends BaseServiceImpl<YsTrusteeship> implements TrusteeshipService {

    @Autowired
    private TrusteeshipMapper trusteeshipMapper;
    @Autowired
    private CourseClassMapper courseClassMapper;

    @Autowired
    public void setMapper(TrusteeshipMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    @Transactional(readOnly = true)
    public YsTrusteeship getTrusteeshipByUniqueId(String uniqueId,Long studentId) {
        YsTrusteeship ysTrusteeship = trusteeshipMapper.getTrusteeshipByUniqueId(uniqueId,studentId);
        if (ysTrusteeship != null){
            ysTrusteeship.initSignUpStatus();
        }
        return ysTrusteeship;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<Boolean> putTrusteeship(YsTrusteeship data) {
        Date currDate = new Date();
        data.setUpdateTime(currDate);
        if (data.getId() == null){
            data.setUniqueId(DateUtil.getTodayyyyMMddHHmm() + RandomUtil.generateNumber(4));
            trusteeshipMapper.insert(data);
        }else {
            trusteeshipMapper.update(data);
        }
        return ResultDTO.successResult();
    }

    @Override
    public void changeShelvesStatus(String ids, Integer shelvesStatus) {
        trusteeshipMapper.updateShelvesStatus(ids,shelvesStatus);
    }

    @Override
    public ResultDTO<Boolean> deleteById(Long id) throws Exception {
        YsTrusteeship data =  trusteeshipMapper.getByPrimaryKey(id);
        if (data!=null){
            Map<String, Object> params = new HashMap<>();
            params.put("classType",5);
            params.put("serviceUniqueId",data.getUniqueId());
            CourseClassDto classDto = courseClassMapper.getByMapParams(params);
            if (classDto != null){
                return ResultDTO.errorResult("当前课程已开班，无法进行删除操作");
            }
            trusteeshipMapper.deleteByPrimaryKey(id);
            return new ResultDTO<>();
        }else{
            return ResultDTO.errorResult(PromptMessage.COURSE_IS_NULL);
        }
    }


}
